import Taro from "@tarojs/taro"
import rootUrl from '../config/rootUrl'

const createRequest = function (method: string): Function {
  return function (url: string, params?: object, contentType?: string): any {
    return new Promise((resolve, reject) => {
      console.log(url, rootUrl.common.dev)
      Taro.request({
        // url: rootUrl.common[process.env.API_ENV] + url,
        url: rootUrl.common[process.env.API_ENV || 'prod'] + url,
        data: params,
        dataType: 'json',
        fail: function (res) {
          reject(res)
        },
        mode: 'cors',
        header: {
          // shopid: 2, // 暂时写死
          shopuuid: '8232f028-b144-46da-9619-8873105de5c1',
          // shopuuid: 'aba6054b-526a-4974-b976-a4b0e7f902d2',
          contentType: '',
          Authorization: `Bearer ${Taro.getStorageSync('authorization')}`,
        },
        method,
        success: function (res) {
          const { code } = res.data
          if (code === 10004) {
            Taro.navigateTo({ url: '/pages/login/index' })
            return
          }

          if (!code) {
            resolve(res.data)
          } else {
            Taro.showToast({
              title: res.data.msg,
              icon: 'none'
            })
          }
        }
      })
    })
  }
}
const get = function (url: string, params?: object, contentType?: string) {
  return createRequest('GET')(url, params, contentType)
}
const post = function (url: string, params?: object, contentType?: string) {
  return createRequest('POST')(url, params, contentType)
}
const del = function (url: string, params?: object, contentType?: string) {
  return createRequest('DELETE')(url, params, contentType)
}
const put = function (url: string, params?: object, contentType?: string) {
  return createRequest('PUT')(url, params, contentType)
}


export const network = {
  get,
  post,
  del,
  put
}
